#include "CTextures.h"

CTextures::CTextures()
{
    //ctor
#ifdef DEBUG
    this->_logger = CLogger::Instance();
#endif
}

CTextures::~CTextures()
{

}

void CTextures::Cleanup()
{
    if (m_surface != NULL)
    {
        SDL_FreeSurface(m_surface);
#ifdef DEBUG
        this->_logger->log(LOG_LEVEL_NOTICE,"CTextures::Cleanup() : Surface deleted");
#endif

    }
    if (glIsTexture(m_texture.texture))
    {
        glDeleteTextures( 1, &m_texture.texture );
#ifdef DEBUG
        this->_logger->log(LOG_LEVEL_NOTICE,"CTextures::Cleanup() : Texture deleted");
#endif
    }
}


/**
  * bool CTextures::loadTexture
  *
  * @param filename
  */
bool CTextures::loadTexture(std::string filename)
{
    CImageLoader *image = new CImageLoader();
    int nOfColors;

    m_surface = image->loadImageFile(filename);
    SDL_DisplayFormat(m_surface);
    if (m_surface == NULL)
    {
        return false;
    }

    nOfColors = m_surface->format->BytesPerPixel; /*get the number of bytes per pixel */

    if (nOfColors == 4)     /* contains an alpha channel*/
    {
        if (m_surface->format->Rmask == 0x000000ff)
            m_texture.textureFormat = GL_RGBA;
        else
            m_texture.textureFormat = GL_BGRA;
    }
    else if (nOfColors == 3)     /* no alpha channel*/
    {
        if (m_surface->format->Rmask == 0x000000ff)
            m_texture.textureFormat = GL_RGB;
        else
            m_texture.textureFormat = GL_BGR;
    }

    /* Have OpenGL generate a texture object handle for us */
    glGenTextures( 1, &m_texture.texture );

    /* Bind the texture object */
    glBindTexture( GL_TEXTURE_2D,m_texture.texture  );

    /* Set the texture's stretching properties */
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

    /*Edit the texture object's image data using the information SDL_Surface gives us */
    glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, m_surface->w, m_surface->h, 0,
                  m_texture.textureFormat, GL_UNSIGNED_BYTE, m_surface->pixels );

    if (m_texture.texture == 0)
    {
#ifdef DEBUG
        this->_logger->log(LOG_LEVEL_WARN,"CTextures::loadTexture() : warning: could not create texture");
#endif
        return false;
    }

    /* set texture struct values */
    m_texture.height = m_surface->h;
    m_texture.width = m_surface->w;

#ifdef DEBUG
    this->_logger->log(LOG_LEVEL_NOTICE,"CTextures::loadTexture() : texture generated from file: %s",filename.c_str());
#endif

    delete image; /* delete image object to free memory */
    return true;
}


TXIMG CTextures::getTexture()
{
    return m_texture;
}

